var clickId;  
var isInsertUrl;//是否插入
var isInsert;
var insertUrl;//诊断按钮 插入模态框里数据  插入的url
/*var ack;*/ //对诊断按钮做处理需要用到ack的值
var id;
var url_page;

$(document).ready(function(){
	
	
	//得到当前用户的故障信息数量  get /fault/list/count
	var fault_number;
	$.ajax({
		type : "get",
		url: "/detection/fault/list/count",
		cache:false,
	    async:false,
		success: function(data){
		   if(data.success){
			     
			   fault_number=data.data;
		   }
		   else{
			   alert("获取信息失败");
		   }
		}
	});
	//alert(fault_number);
	
	//分页点击框动态实现 
	//默认设置当前点击是1  显示第一页内容
	var page_click=1; //向后台传页码默认是1
	
	var fault_numbertest=78;//测试用
	var page_count= Math.ceil(fault_number/15); //计算生成几页
	var page_nav;  //导航栏名称
	var reg= /^[0-9]+.?[0-9]*$/; //判断是否是数字
	url_page="/detection/fault/list/"+page_click;  //拼接的url 赋初始值
	
	//生成分页导航条  先获取到fault_number 再进行生成
	//如果页数大于3
	if(reg.test(parseInt(fault_number)) ){
		if(page_count>=3){
			page_nav='<li><a href="javascript:;" >&laquo;&laquo;</a></li>'
				+'<li><a href="javascript:;" >&laquo;</a></li>'
				+'<li><a id="page_first" href="javascript:;">1</a></li>'
				+'<li><a id="page_mid" href="javascript:;">2</a></li>'
				+'<li><a id="page_last" href="javascript:;">3</a></li>'
				+'<li><a href="javascript:;">&raquo;</a></li>'
				+'<li><a href="javascript:;">&raquo;&raquo;</a></li>';
			$('#diagnosis_ul').html(page_nav);//将分页加载到html中
			//如果页面数目大于3 生成一个三页的分页栏
			
		}
		//页数小于3页
		else{
			//填充分页栏前面« 和 ««
			page_nav='<li><a href="javascript:;" >&laquo;&laquo;</a></li>'
				+'<li><a href="javascript:;" >&laquo;</a></li>';
			for(i=1; i<=page_count; i++){
				//填充页数 1页或2页
				page_nav += '<li><a id="page_'+i+'" href="javascript:;">'+i+'</a></li>';
			}
			
			//补充分页栏后面» 和 »»
			page_nav += '<li><a href="javascript:;">&raquo;</a></li>'
				+'<li><a href="javascript:;">&raquo;&raquo;</a></li>';
			$('#diagnosis_ul').html(page_nav);//将分页加载到html中
		}
	}
	
	//导航栏点击事件
	$("a").click(function(){      
		 cur_click=$(this).text();
		 //alert(cur_click);
		 //alert(parseInt($('#page_first').text())+1);
		 if(page_count>=3){
			 if(cur_click=="««"){
					 $('#page_first').html("1");
					 $('#page_mid').html("2");
					 $('#page_last').html("3");
			 }
			 else if(cur_click=="«"){
				 var first=parseInt($('#page_first').text());
				 if(first>1){
					 $('#page_first').html($('#page_first').text()-1);
					 $('#page_mid').html($('#page_mid').text()-1);
					 $('#page_last').html($('#page_last').text()-1);
				 }
			 }
			 else if(cur_click=="»"){
				 var last=parseInt($('#page_last').text());
				 if(last<page_count){
					 $('#page_first').html(parseInt($('#page_first').text())+1);
					 $('#page_mid').html(parseInt($('#page_mid').text())+1);
					 $('#page_last').html(parseInt($('#page_last').text())+1);
				 }
			 }
			 else if(cur_click=="»»"){
				 $('#page_first').html(page_count-2);
				 $('#page_mid').html(page_count-1);
				 $('#page_last').html(page_count);
			 }
			 else if(reg.test(parseInt(cur_click)) ){
				 page_click=cur_click;
				 url_page="/detection/fault/list/"+page_click;  //拼接获取相关页的url
				 //alert(url_page);
				 
				 //将当前页放在中间位置  如果当前页不是第一页或最后一页
				 
			 }
		 }
		 else{//页数小于3
			 cur_click=$(this).text();
			 //如果是按数字   给page_click赋值
			 if(reg.test(parseInt(cur_click)) ){
				 page_click=cur_click;
				 //alert(page_click);
			 }
			 
			 url_page="/detection/fault/list/"+page_click;  //拼接获取相关页的url
			 //alert(url_page);
			 
		 }
		 //每点击一次事件 调用一次
		 getDiagnosisTable();
		 
	 });
	//先调用一次  初始化表格
	getDiagnosisTable();
		
});//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

//时间处理格式
function timeFormat(timeStamp){
	var time = new Date(timeStamp);//改为时间戳
	
	var year = time.getFullYear();
	var month = time.getMonth()+1;
	//month++;//month 一月是0 二月是1
	if(month<10){
		month='0'+month;
	}
	var day = time.getDate();
	if(day<10){
		day='0'+day;
	}
	var hour = time.getHours();
	if(hour<10){
		hour='0'+hour;
	}
	var minutes = time.getMinutes();
	if(minutes<10){
		minutes='0'+minutes;
	}
	var second = time.getSeconds();
	if(second<10){
		second='0'+second;
	}
	var result = year+'-'+month+'-'+day+' '+hour+':'+minutes+':'+second;
	return result;
}

//如果当前点击的是数字  向后台取相应页的日志
function getDiagnosisTable(){
	var diagnosis_row='';
	
	$.ajax({
		type : "get",
		url: url_page,
		cache:false,
		success: function(data){
		
		   if(data.success){
			   for(var i = 0; i < data.data.length; i++){    //获取后台传过来的url中的数据
				   
		            id = data.data[i].id;
		            var occurTime = data.data[i].gmtCreate; //时间戳
		            occurTime = timeFormat(occurTime);
		            //occurTime = new Date(occurTime).toLocaleString();
		            var violateRule = data.data[i].rule.ruleName+"; "+data.data[i].rule.description;  //需要拼接
		            var hostName = data.data[i].rule.hostId;  //规则的hostid
		            var alarmingWay = data.data[i].media.mediaName;
		            var send = data.data[i].isSent;
		            var sendStatus;
			            switch(send){         //对违反规则的严重程度进行判断,并进行显式转换
				    		case 1:
				    			sendStatus = 'status-circle status-running';
				    			break;
				    		case 0:
				    			sendStatus = 'status-circle status-crash';
				    		 	break;
				    		default:
				    			sendStatus = 'status-metro status-crash';
			    		};
		            var ack = data.data[i].isAcked;
		            var ackStatus;
			            switch(ack){         //对违反规则的严重程度进行判断,并进行显式转换
				    		case 1:
				    			ackStatus = 'status-circle status-running';
				    			break;
				    		case 0:
				    			ackStatus = 'status-circle status-crash';
				    		 	break;
				    		default:
				    			ackStatus = 'status-metro status-crash';
			    		};
		           
		            var ruleStatus = data.data[i].gmtModified;  ///wrong   没用
		            var send_ack_Status;
			            if(send==1 && ack==1){
			            	send_ack_Status = 'status-circle status-running';
			            }else{
			            	send_ack_Status = 'status-circle status-crash';
			            }
		            
		            var severe = data.data[i].rule.severe;
		            var severeStatus;
			            switch(severe){         //对违反规则的严重程度进行判断,并进行显式转换
				    		case 1:
				    			severeStatus = '<span class="status-metro status-low">Low</span>';
				    			break;
				    		case 2:
				    			severeStatus = '<span class="status-metro status-warning">Warning</span>';
				    		 	break;
				    		case 3:
				    			severeStatus = '<span class="status-metro status-high">High</span>';
				    		 	break;
				    		case 4:
				    			severeStatus = '<span class="status-metro status-higher">Higher</span>';
				    		 	break;
				    		case 5:
				    			severeStatus = '<span class="status-metro status-serious">Serious</span>';
				    		 	break;
				    		case 6:
				    			severeStatus = '<span class="status-metro status-disaster">Disaster</span>';
				    		 	break;
				    		default:
				    			sendStatus = '<span class="status-metro status-low">Low</span>';
			    		};
		    		
		            diagnosis_row += '<tr><td class="faultId" id="faultId" >' + id + '</td><td>' 
		            							+ occurTime + '</td><td>' 
		            							+ violateRule + '</td><td>' 
		            							+ hostName + '</td><td id="name">' 
		            							+ alarmingWay + '</td><td><div class="'
		            							+ sendStatus +'"></div></td><td><div class="'
		            							+ ackStatus +'"></div></td><td><div class="'
		            							+ send_ack_Status +'"></div></td><td>' 
		            							+ severeStatus 
		            							+'</td><td><button id="diagBtn" onclick="diagBtn(this)" data-toggle="modal"  type="button"  class="btn btn-default">Diagnosis</button></td></tr>';
		            							
			   }
		   }
	       $('#diagnosis_body').html(diagnosis_row);//将每一行的数据加载到html中的id为config_body的tbody中
	       //console.log(row);
	       $('#diagnosis_show').footable();//对footable进行初始化
	       //alert("diagnosis_row hou "+diagnosis_row);
	      
		}
	
	});	
}

//诊断按钮   获取所诊断故障的id
//obj 表示只对点击行进行操作
function diagBtn(obj){
	var x = $(obj).parent().parent().find("td");
    clickId =  x.eq(0).text();  //得到点击行的id值
    
    //查看用户点击当前的 原因插入状态
    isInsertUrl ='/detection/fault/list/'+clickId+'/diag';
    //用户自己插入原因的url
    insertUrl = '/detection/fault/list/'+clickId+'/reason/insertion';
    
	//alert(insertUrl);
	
    //等待
    //var y =  x.eq(9).text();
    //alert(y);
    //$('#diagBtn').html("Wait...");
    
    //获取diagnosis的状态  查看用户是否插入
	$.ajax({
		type:"get",
		url: isInsertUrl,   
		cache:false,
		async:false,
		success: function(data){
			if(data.success){
				isInsert = true;
			}
			else{
				isInsert = false;
			}
		}
	});
	
	//(ack==1 && isInsert==true) || (ack==0 && isInsert==true)   查询模态框
	if(isInsert){
		
		//获取查询模态框属性相应的值
		// 1.failure cause id  2.failure cause   3.rule id   4.rule detail(拼接) 
		var failureCauseId;
		var failureCause;
		var ruleId;
		var ruleDetail;
		var ruleMetric;
		var ruleFunction;
		var ruleParameter;
		var ruleOperator;
		var ruleThreshold;
		
		
		$.ajax({
			type:"get",
			url: isInsertUrl,   //???????
			cache:false,
			async:false,
			success: function(data){
				if(data.success){
					failureCauseId = data.data.faultId;//ok
					failureCause = data.data.faultReason;//ok
					ruleId = data.data.ruleId;//ok
					
					ruleMetric = data.data.faultExtend.rule.metric.metricName;
					ruleFunction = data.data.faultExtend.rule.checkFunc.funcName;   //funtion  func
					ruleParameter =  data.data.faultExtend.rule.funcParameter;
					ruleOperator =  data.data.faultExtend.rule.operator;
					ruleThreshold = data.data.faultExtend.rule.triggerThreshold;
					
					ruleDetail = '({'+ruleMetric+' '+ruleFunction+'('+ruleParameter+')}'+ruleOperator+ruleThreshold+')';
					
				}
				
			}
		});
		/*alert(ruleDetail);*/
		
		$("#failureCauseId").val(failureCauseId);
		$("#failureCauseArea").val(failureCause);
		$("#ruleId").val(ruleId);
		$("#ruleDetail").val(ruleDetail);
		
		//selectDiagModal
		$("#selectDiagModal").modal('show');
		
	}
	
	//插入模态框 insertDiagModal
	else{
		
		var rule_name_display;
		var log_display = '';
		$.ajax({
			type:"get",
			url: isInsertUrl,   //返回false
			cache:false,
			async:false,
			success: function(data){
				if(!data.success){
					var name = data.data.faultExtend.rule.ruleName;
					var descript = data.data.faultExtend.rule.description;
					rule_name_display = '规则名称:'+name+'  描述:'+descript;
					
					//alert('长度：'+data.data.exceptLogs.length);
					if(data.data.exceptLogs.length!=0){
						for(var i=0; i<data.data.exceptLogs.length; i++){
							
							var logtime = data.data.exceptLogs[i].logtime;
							logtime = timeFormat(logtime);
							var software = data.data.exceptLogs[i].software;
							var content = data.data.exceptLogs[i].content;
							log_display += logtime
										+'['+software+']'
										+'{'+content+'};\n';
						}
					}else{
						log_display +="日志片段为空";
					}
					
					//alert("content:"+log_display);
				}
				
			}
		});
		//写入页面
		$("#rule_display").val(rule_name_display);
		$("#log_display").html(log_display);
		//显示插入界面
		$("#insertDiagModal").modal('show');
		
		//填写诊断原因模态框(insertDiagModal)的确认按钮  数据传入后台
		$("#metricConfirm").click(function(){ 
			//var diag_result=$("#diag_result").val();
			var fault_reason=$("#fault_reason").val();
			//alert("diag_result:"+diag_result+"  fault_reason"+fault_reason);
			if(fault_reason!=""){
				$.ajax({
					type:'post',//提交数据的方法类型
			        dataType: 'text',//预期服务器返回的数据类型
					url: insertUrl,//后台接收参数的文件地址
					cache:false,
					data:{
						//'diag':diag_result,///??后台？？？
						'reason':fault_reason,
					},
					success : function(data) {
			            alert("故障诊断数据插入成功");
			    		//getKeyTable();
			            //刷新表格
			            getDiagnosisTable();
			        },
			        error : function(jqXHR, textStatus, errorThrown){
			        	/*alert(jqXHR.responseText);
			            alert(jqXHR.status);
			            alert(jqXHR.readyState);
			            alert(jqXHR.statusText);*/
			        	alert("故障诊断数据插入失败");
			        }
					
				});
				$("#insertDiagModal").modal('hide');
				
			}else{
				alert("故障原因不能为空");
			}
			

		});//metricConfirm
		
		
	}//else
	
	
    

}




